<script setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import api from '@/api/index.js'
import { useUserStore } from '@/stores/modules/user';
import { phoneRule, emailRule } from '@/utils/checkRule.js'

const userSrore = useUserStore()
// 弹窗标题
const title = '修改个人信息'
// 表单数据
const formData = ref({
  name: '',
  phone: '',
  email: '',
  ...userSrore.userInfo
})
// 是否显示弹窗
const show = ref(false);
// 弹窗显示状态切换时触发
const afterOpenChange = bool => {
  if (!bool) {
    formData.value = {
      name: '',
      phone: '',
      email: '',
      ...userSrore.userInfo
    }
  }
};
// 提交按钮loading状态
const submitLoading = ref(false)
// 表单提交，验证通过了
const onFinish = async values => {
  submitLoading.value = true
  let params = { ...userSrore.userInfo, ...formData.value, ...values }
  await api.updateUserInfo(params)
  userSrore.setUserInfo(params)
  message.success('编辑成功');
  show.value = false
  setTimeout(() => {
    submitLoading.value = false
  }, 30);
};
// 验证失败
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
// 打开弹窗
const open = () => {
  show.value = true;
};
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value
    .validateFields()
    .then(onFinish)
    .catch(onFinishFailed);
}
defineExpose({ open })
</script>

<template>
  <a-drawer :maskClosable="false" :closable="false" destroyOnClose v-model:open="show" class="custom-class"
    root-class-name="root-class-name" :title="title" placement="right" @after-open-change="afterOpenChange">
    <a-form ref="formRef" :model="formData" layout="vertical" autocomplete="off" @finish="onFinish"
      @finishFailed="onFinishFailed">
      <a-form-item label="姓名" name="name" :rules="[{ required: true, message: '请输入' }]">
        <a-input v-model:value="formData.name" allowClear />
      </a-form-item>
      <a-form-item label="电话" name="phone" :rules="phoneRule">
        <a-input v-model:value="formData.phone" allowClear />
      </a-form-item>
      <a-form-item label="邮箱" name="email" :rules="emailRule">
        <a-input v-model:value="formData.email" allowClear />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex;gap: 5px;">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading">提交</a-button>
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>